<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="线索名称" prop="name">
            <el-input v-model="pd.queryParams.name" placeholder="请输入线索名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="客户来源" prop="source">
            <el-select v-model="pd.queryParams.source" placeholder="请选择客户来源" clearable>
              <el-option v-for="dict in hrp_lead_source" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户阶段" prop="stage">
            <el-select v-model="pd.queryParams.stage" placeholder="请选择客户阶段" clearable>
              <el-option v-for="dict in hrp_lead_source" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="失去原因" prop="lostReason">
            <el-select v-model="pd.queryParams.lostReason" placeholder="请选择失去原因" clearable>
              <el-option v-for="dict in hrp_lead_lost_reason" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="下次跟单时间" style="width: 308px">
            <el-date-picker
              v-model="dateRangeNextTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['hrp:lead:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()" v-hasPermi="['hrp:lead:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()" v-hasPermi="['hrp:lead:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hrp:lead:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.leadList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="线索ID" align="center" prop="id" v-if="false" />
        <el-table-column label="线索名称" align="center" prop="name" />
        <el-table-column label="客户id" align="center" prop="partnerId" />
        <el-table-column label="归属销售" align="center" prop="salesId" />
        <el-table-column label="客户来源" align="center" prop="source">
          <template #default="scope">
            <dict-tag :options="hrp_lead_source" :value="scope.row.source" />
          </template>
        </el-table-column>
        <el-table-column label="客户阶段" align="center" prop="stage">
          <template #default="scope">
            <dict-tag :options="hrp_lead_source" :value="scope.row.stage" />
          </template>
        </el-table-column>
        <el-table-column label="失去原因" align="center" prop="lostReason">
          <template #default="scope">
            <dict-tag :options="hrp_lead_lost_reason" :value="scope.row.lostReason" />
          </template>
        </el-table-column>
        <el-table-column label="下次跟单时间" align="center" prop="nextTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.nextTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['hrp:lead:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['hrp:lead:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改线索、商机-客户跟单对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="500px" append-to-body>
      <el-form ref="leadFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-form-item label="线索名称" prop="name">
          <el-input v-model="pd.form.name" placeholder="请输入线索名称" />
        </el-form-item>
        <el-form-item label="客户来源" prop="source">
          <el-select v-model="pd.form.source" placeholder="请选择客户来源">
            <el-option v-for="dict in hrp_lead_source" :key="dict.value" :label="dict.label"
                       :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户阶段" prop="stage">
          <el-select v-model="pd.form.stage" placeholder="请选择客户阶段">
            <el-option v-for="dict in hrp_lead_source" :key="dict.value" :label="dict.label"
                       :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="失去原因" prop="lostReason">
          <el-select v-model="pd.form.lostReason" placeholder="请选择失去原因">
            <el-option v-for="dict in hrp_lead_lost_reason" :key="dict.value" :label="dict.label"
                       :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下次跟单时间" prop="nextTime">
          <el-date-picker clearable
                          v-model="pd.form.nextTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择下次跟单时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Lead" lang="ts">
import { listLead, getLead, delLead, addLead, updateLead } from '@/api/hrp/lead';
import { LeadVO, LeadQuery, LeadForm } from '@/api/hrp/lead/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { hrp_lead_source, hrp_lead_lost_reason } = toRefs<any>(proxy?.useDict('hrp_lead_source', 'hrp_lead_lost_reason'));


const dateRangeNextTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const leadFormRef = ref<ElFormInstance>();

const initFormData: LeadForm = {
  name: undefined,
  partnerId: undefined,
  salesId: undefined,
  source: undefined,
  stage: undefined,
  lostReason: undefined,
  nextTime: undefined,
  remark: undefined,
}
const pd = reactive({
  leadList: <LeadVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  ids: <Array<string | number>>([]),
  single: true,
  multiple: true,
  total: 0,
  form: <LeadForm>{...initFormData},
  queryParams: <LeadQuery>{
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    partnerId: undefined,
    salesId: undefined,
    source: undefined,
    stage: undefined,
    lostReason: undefined,
    params: {
      nextTime: undefined,
    }
  },
  rules: <ElFormRules>{
    name: [
      { required: true, message: "线索名称不能为空", trigger: "blur" }
    ],
    partnerId: [
      { required: true, message: "客户id不能为空", trigger: "change" }
    ],
    salesId: [
      { required: true, message: "归属销售不能为空", trigger: "change" }
    ],
    source: [
      { required: true, message: "客户来源不能为空", trigger: "change" }
    ],
    stage: [
      { required: true, message: "客户阶段不能为空", trigger: "change" }
    ],
    lostReason: [
      { required: true, message: "失去原因不能为空", trigger: "change" }
    ],
    nextTime: [
      { required: true, message: "下次跟单时间不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

// const { queryParams, form, rules } = toRefs(data);

/** 查询线索、商机-客户跟单列表 */
async function getList() {
  pd.loading = true;
  pd.queryParams.params = {};
  proxy?.addDateRange(pd.queryParams, dateRangeNextTime.value, 'NextTime');
  const res = await listLead(pd.queryParams);
  pd.leadList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = {...initFormData};
  leadFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeNextTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: LeadVO[]) {
  pd.ids = selection.map(item => item.id);
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.visible = true;
  pd.dialog.title = "添加线索、商机-客户跟单";
}

/** 修改按钮操作 */
async function handleUpdate(row?: LeadVO) {
  reset();
  const _id = row?.id || pd.ids[0]
  const res = await getLead(_id);
  Object.assign(pd.form, res.data);
  pd.dialog.visible = true;
  pd.dialog.title = "修改线索、商机-客户跟单";
}

/** 提交按钮 */
function submitForm() {
  leadFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateLead(pd.form).finally(() =>  pd.buttonLoading = false);
      } else {
        await addLead(pd.form).finally(() =>  pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: LeadVO) {
  const _ids = row?.id || pd.ids;
  await proxy?.$modal.confirm('是否确认删除线索、商机-客户跟单编号为"' + _ids + '"的数据项？').finally(() => pd.loading = false);
  await delLead(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('hrp/lead/export', {
    ...pd.queryParams
  }, `lead_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
